<?php
/**
 * Copyright (C) 2007 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
// Log levels
define("L_OFF", 0); // No log
define("L_BASIC", 1); // Log Basic
define("L_MEDIUM", 2); // Log Medium
define("L_HI", 4); // Log Hi
 
class Log {
  protected static $errorLogFile;
  protected static $logLevel = L_MEDIUM;
  protected static $print = false;
  /**
   * SetLogFiles
   */
  public static function setLog($LogFile, $logLevel=L_MEDIUM, $print=false, 
                                                                    $die=true){
    if($logLevel == L_OFF) {
      self::$logLevel = L_OFF;
      return false;
    } else {
      if (!self::$errorLogFile = @fopen($LogFile, "a")) {
        header('HTTP/1.0 500 Internal Server Error');
        $log = "Cannot open " . $LogFile . " file.\n" .
                    "Logs are not writable, set them to 777";        
        error_log($log, 0);
        if($die) {
          die($log);
        }else {
          self::$logLevel = L_OFF;
          throw new Exception($log);
        }
      }
    }
    self::$logLevel = $logLevel;
    self::$print = $print;
  }
  
  public static function basic($log) {
    return Log::__log($log, L_BASIC);
  }
  
  public static function medium($log) {
    return Log::__log($log, L_MEDIUM);
  }
  
  public static function hi($log) {
    return Log::__log($log, L_HI);
  }
  
  protected static function __log($log, $level=L_BASIC){
    if(Log::$logLevel >= $level && !empty($log)) {
      fwrite(Log::$errorLogFile,
      sprintf("\n%s: \n%s\n", date("D M j G:i:s T Y"), $log));
      if(self::$print) {
        echo $log;
      }
      return true;
    }
    return false;
  }
}